<template>
    <div class="my-search">
        <el-form :inline="true" label-width="auto" size="mini" class="my-search-form">
            <template v-for="(item, index) in fields">
                <template v-if="index < baseNumber">
                    <my-search-item :key="item.field" :item="item" :base-number="baseNumber" :index="index" label-width="auto" :base="true">
                        <template v-if="item.slotName" #[item.slotName]>
                            <slot :name="item.slotName"></slot>
                        </template>
                    </my-search-item>
                </template>
                
            </template>
            
            
            <el-form-item>
                <template v-if="fields.length > baseNumber">
                    <el-popover ref="searchpop" v-model="visible" popper-class="comm-search" :width="popoverWidth" placement="bottom" trigger="click">
                        <div style="max-height: 380px; overflow: auto; margin-bottom: 8px">
                            <el-form :label-width="labelWidth" size="mini">
                                <template v-for="(item, mm) in fields">
                                    <my-search-item v-if="mm >= baseNumber" :key="item.field" :item="item" :base-number="baseNumber" :index="mm" :label-width="labelWidth">
                                        <template v-if="item.slotName" #[item.slotName]>
                                            <slot :name="item.slotName"></slot>
                                        </template>
                                    </my-search-item>
                                </template>
                            </el-form>
                        </div>
                        <div :style="{ textAlign: searchBtnAlign }">
                            <el-button size="mini" type="primary" @click="search">{{ searchButtonText }}</el-button>
                            <el-button size="mini" type="default" @click="reset">{{ resetButtonText }}</el-button>
                        </div>
                        <el-button slot="reference" style="margin-right: 8px" type="default" size="mini" @click.stop.prevent="handleOpenMore">更多查询条件</el-button>
                    </el-popover>
                </template>
                <el-button size="mini" type="primary" @click="search">{{ searchButtonText }}</el-button>
                <el-button size="mini" type="default" @click="reset">{{ resetButtonText }}</el-button>
            </el-form-item>
            <el-form-item>
                <slot></slot>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import mySearchItem from './include/item';
export default {
    name: 'MySearch',
    components: { 'my-search-item': mySearchItem },
    props: {
        popoverWidth: { type: Number, default: 440 },
        // label宽度
        labelWidth: {
            type: String,
            default: '400px'
        },
        // 默认显示前3个条件
        baseNumber: {
            type: Number,
            default: 3
        },
        // 查询按钮位置 left center right
        searchBtnAlign: {
            type: String,
            default: 'center'
        },
        // 是否过滤表单的空值
        isFilterForm: {
            type: Boolean,
            default: false
        },
        // 触发方式 click/focus/hover/manual
        trigger: {
            type: String,
            default: 'click'
        },
        // 选择器是否添加 "全部" 这个下拉选项选项
        selectIsAddAll: {
            type: Boolean,
            required: false,
            default: true
        },
        searchButtonText: {
            type: String,
            default: '查询'
        },
        resetButtonText: {
            type: String,
            default: '重置'
        },
        // 条件列表
        fields: {
            type: Array,
            default: () => [
                {
                    field: 'text',
                    label: '文本：',
                    type: 'text', // text
                    value: ''
                },
                {
                    field: 'choose',
                    label: '选择：',
                    type: 'select', // select
                    multiple: false,
                    value: '',
                    options: [

                    ],
                    change: val => { }
                },
                {
                    label: '数字区间：',
                    field: 'number',
                    type: 'numberSection', // numberSection
                    options: [
                        {
                            field: 'jzmjQ',
                            value: ''
                        },
                        {
                            field: 'jzmjZ',
                            value: ''
                        }
                    ]
                },
                {
                    label: '日期区间：',
                    field: 'date',
                    type: 'daterange', // daterange
                    value: [],
                    options: [
                        {
                            field: 'dateQ',
                            value: ''
                        },
                        {
                            field: 'dateZ',
                            value: ''
                        }
                    ],
                    change: value => {
                        // this.changxm(value);
                    }
                },
                {
                    label: '月份区间：',
                    field: 'monthrange',
                    type: 'monthrange', // monthrange
                    value: [],
                    options: [
                        {
                            field: 'monthQ',
                            value: ''
                        },
                        {
                            field: 'monthZ',
                            value: ''
                        }
                    ],
                    change: value => {
                        // this.changxm(value);
                    }
                },
                {
                    label: '年：',
                    field: 'year',
                    type: 'year', // year
                    value: ''
                },
                {
                    label: '月：',
                    field: 'month',
                    type: 'month', // month
                    value: ''
                },
                {
                    label: '日：',
                    field: 'day',
                    type: 'date', // date
                    value: ''
                },

                {
                    label: '我比较特殊,我的LABEL是超长的,请添加自定义样式：',
                    field: 'zzsrq',
                    type: 'text',
                    value: '',
                    labelWidth: '166px', // label的宽度
                    style: {
                        // form-item整体的自定义样式
                        flex: 'none',
                        width: '100%'
                    }
                },
                {
                    label: '树形下拉选择：', // 目前组织机构专用
                    field: 'zzjgId',
                    placeholder: '请选择',
                    type: 'treeSelect', // treeSelect
                    value: null,
                    options: [],
                    change: value => {
                        // this.selectTree(value);
                    }
                }
            ]
        }
    },
    data() {
        return {
            visible: false
        };
    },
    created() {
        this.selectAddAllOption();
        this.fields.forEach(item => {
            if (item.label.indexOf(':') != -1 || item.label.indexOf('：') != -1) {
                item.label = item.label.replace(/\:|：/, '');
            }
            item.label = item.label + ':';
        });
    },
    methods: {
        handleOpenMore() {
            // this.visible = !this.visible;
            // this.$store.dispatch('mySearch/toggleVisible');
        },
        /**
         * @method selectAddAllOption
         * @description 下拉类型添加全部
         * @example
         */
        selectAddAllOption() {
            if (!this.selectIsAddAll) {
                return;
            } else {
                this.fields.forEach(item => {
                    if (item.type === 'select' && item.options) {
                        if (!item.options.some(option => option.label === '全部')) {
                            item.options = [{ label: '全部', value: '' }].concat(item.options);
                        }
                    }
                });
            }

        },
        /**
         * @method search
         * @description 通知查询操作
         * @example
         */
        search() {
            this.visible = false;
            // this.$store.dispatch('mySearch/toggleVisible');
            this.$emit('onSearch', this.getFormData());
        },
        /**
         * @method reset
         * @description 通知重置操作
         * @example
         */
        reset() {
            this.resetFormData();
            this.visible = false;
            // this.$store.dispatch('mySearch/toggleVisible');
            this.$emit('onReset', this.getFormData());
        },
        /**
         * @method getFormData
         * @description 获取表单数据
         * @example
         */
        getFormData() {
            let formData = {};
            for (const item of this.fields) {
                if (!item.field) {
                    continue;
                }
                let obj = {};
                switch (item.type) {
                    case 'select': // 下拉选择
                        formData[item.field] = item.multiple ? (item.value ? item.value : []) : item.value;
                        break;
                    case 'numberSection': // 数字区间
                        obj = this.getNumberSectionValue(item);
                        for (const key in obj) {
                            formData[key] = obj[key];
                        }
                        break;
                    case 'percentSection': // 百分比 区间
                        obj = this.getPercentSectionValue(item);
                        for (const key in obj) {
                            formData[key] = obj[key];
                        }
                        break;
                    case 'daterange': // 日期区间
                        obj = this.getDaterangeValue(item);
                        for (const key in obj) {
                            formData[key] = obj[key];
                        }
                        // 是否有NULl
                        if (item.isNullVisible && item.defaultIsNull) {
                            formData[item.isNullField] = item.defaultIsNull;
                        } else {
                            delete formData[item.isNullField];
                        }
                        break;
                    case 'monthrange': // 月份区间
                    case 'datetimerange': // 日期区间
                        obj = this.getDaterangeValue(item);
                        for (const key in obj) {
                            formData[key] = obj[key];
                        }
                        break;
                    case 'text': // 文本
                    case 'treeSelect': // 树形组件
                    default:
                        formData[item.field] = item.value;
                        break;
                }
            }
            // 过滤空值
            if (this.isFilterForm) {
                formData = this.$utils.ObjFilter(formData);
            }
            return formData;
        },

        /**
         * @method resetFormData
         * @description 重置表单数据
         * @example
         */
        resetFormData() {
            for (const item of this.fields) {
                if (item.type === 'treeSelect') {
                    // 树形组件（特殊处理）
                    if (item.options.length > 0) {
                        // item.value = item.options[0].id || null;
                        item.value = null;
                    }
                } else if (item.type === 'select') {
                    // 下拉选择器
                    item.value = item.multiple ? [] : '';
                } else if (item.type === 'numberSection' || item.type === 'percentaSection') {
                    // 数字区间
                    if (item.options && Array.isArray(item.options)) {
                        item.options.forEach(option => {
                            option.value = '';
                        });
                    }
                } else if (item.type === 'daterange' || item.type === 'datetimerange' || item.type === 'monthrange') {
                    // 日期区间 日期时间区间 月份区间
                    item.value = [];
                    if (item.options && Array.isArray(item.options)) {
                        item.options.forEach(option => {
                            option.value = '';
                        });
                    }
                    if (item.isNullVisible) {
                        item.defaultIsNull = false;
                        item.disabled = false;
                    }
                } else {
                    item.value = '';
                }
            }
        },

        /**
         * @method getNumberSectionValue
         * @description 获取数字区间类型的值
         * @param { object } item
         * @example
         */
        getNumberSectionValue(item) {
            const obj = {};
            if (item.options && Array.isArray(item.options)) {
                item.options.forEach(item => {
                    obj[item.field] = item.value;
                });
            }
            return obj;
        },
        getPercentSectionValue(item) {
            const obj = {};
            if (item.options && Array.isArray(item.options)) {
                item.options.forEach(item => {
                    obj[item.field] = item.value;
                });
            }
            return obj;
        },

        /**
         * @method getDaterangeValue
         * @description 获取日期区间的值
         * @param { object } item
         * @example
         */
        getDaterangeValue(item) {
            const obj = {};
            if (item.value && item.options && Array.isArray(item.value) && Array.isArray(item.options)) {
                item.options.forEach((option, i) => {
                    if (item.value.length == 2) {
                        option.value = item.value[i];
                    } else {
                        option.value = '';
                    }
                    obj[option.field] = option.value;
                });
            } else {
                item.options.forEach((option, i) => {
                    obj[option.field] = '';
                });
            }

            return obj;
        },
        // 关闭
        close() {
            this.visible = false;
            // this.$store.dispatch('mySearch/toggleVisible');
        }
    }
};
</script>
<style lang="scss" scoped>
.my-search {
    background: #fff;
    padding: 8px;
    // border-bottom: 1px solid rgb(238, 238, 238);
    &-form {
        // height: 28px;
        .el-form-item {
            margin-bottom: 8px;
        }

        :deep(.el-form-item) {
            vertical-align: text-bottom;
            .el-form-item__label {
                font-weight: unset;
            }
            .el-form-item__content {
                float: left;
                .el-date-editor {
                    width: 260px !important;
                }
            }
            .el-form-item__label-wrap {
                margin: 0 !important;
            }
        }
        .el-input__inner {
            height: 30px;
            line-height: 30px;
            &.el-date-editor {
                padding: 3px 5px;
            }
        }
        :deep(.vue-treeselect) {
            width: 180px;
            .vue-treeselect__control,
            .vue-treeselect__placeholder,
            .vue-treeselect__single-value {
                height: 28px !important;
                line-height: 28px !important;
                margin: 0;
            }
        }

        .el-form-item__label {
            height: 30px;
            line-height: 30px;
        }
        .el-form-item__content {
            height: 30px;
            line-height: 1px;
        }
        .el-input__icon {
            height: 30px;
            line-height: 30px;
        }
        .el-range-editor--mini .el-range-separator {
            line-height: 17px;
        }
    }
}
</style>
